package cuid.sc20.laboratory.controller;

import cuid.sc20.laboratory.exception.UserException;
import cuid.sc20.laboratory.utils.CookieUtils;
import cuid.sc20.laboratory.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/login")
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    private StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/goToLogin")
    public String goToLogin(@RequestParam("message") String message, Map<String, String> map) {
        map.put("message", message);
        return "login";
    }

    @PostMapping("/do")
    public String doLogin(@RequestParam("name") String name, @RequestParam("password") String password, HttpServletResponse response) {
        //-- 约定：用户名和密码都是admin
        if (Objects.equals("admin", name) && Objects.equals("admin", password)) {
            //-- 生成Token
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("role", "美少女战士");
            //-- 给null 就是默认过期时间 3分钟
            String token = JwtUtils.createHmacJWT(map, null);
            logger.info("登录生成Token:" + token);
            //-- Cookie本身是没有过期时间，但是Cookie中的value 是有过期时间的！
            //-- 响应头：setCookie：authorization=token
            //-- 下次发送请求时，就会自动携带上 authorization=token 。位于Cookie
            CookieUtils.setCookie(response, "authorization", token,null);
            //-- 把Token放入到Redis中
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set(token, token, 2, TimeUnit.MINUTES);
            //-- 登录完成后回到首页！
            return "index";
        }
        throw new UserException("用户名不存在或者密码不正确");
    }
}